<template>
  <div class="chat-line" :class="self ? 'line-reverse':''">
    <div class="photo">
      <img :src="photoUrl" alt="">
    </div>
    <div class="talk">
      <div class="name" v-if="!self">{{ name }}</div>
      <div class="chat" :class="self ? 'chat-right':'chat-left'">
        <div class="chat-box" :class="self ? 'chat-box-right':'chat-box-left'">
          <span>{{ content }}</span>
        </div>
        <div class="time">{{ time_display }}</div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';
import { login } from '../api/api';
import { useStore } from '../stores';
import { useDefaultPhoto } from '../stores/photo';

const props = defineProps({
  userid: {
    type: String,
    require: true
  },
  time: {
    type: String,
    default: ''
  },
  content: {
    type: String,
    default: ''
  }
})

const photoUrl = ref(useDefaultPhoto().photoUrl)
const name = ref('Unknown')
// 判断是否为自己的消息
const store = useStore()
const self = computed(() => {
  if (props.userid === store.id) {
    return true
  } else {
    return false
  }
})
// 处理时间格式
const time_display = computed(() => props.time.replaceAll('-', '/'))

// get userinfo
if (props.userid) {
  login(props.userid).then(response => {
    name.value = response.data.name
    if (response.data.photo) {
      photoUrl.value = response.data.photo
    }
  }).catch(error => console.log(error))
}
</script>

<style scoped>
img {
  height: 100%;
  width: 100%;
}
.chat-line {
  min-height: 5rem;
  width: 100%;
  display: flex;
  flex-direction: row;
}
.line-reverse {
  flex-direction: row-reverse;
}
.photo {
  height: 4rem;
  width: 4rem;
  border-radius: 50%;
  overflow: hidden;
}
.talk {
  height: 100%;
  width: calc(70% - 4rem);
}
.name {
  padding-left: 1rem;
  height: 1.25rem;
  line-height: 1.25rem;
}
.chat {
  display: flex;
}
.chat-left {
  flex-direction: row;
  padding-left: 20px;
}
.chat-right {
  flex-direction: row-reverse;
  padding-right: 20px;
}
.chat-box {
  display: inline-block;
  height: fit-content;
  width: fit-content;
  max-width: 100%;
  border-radius: .25rem;
  padding: .5rem;
  margin-top: .25rem;
}
.chat-box-left {
  background-color: var(--el-fill-color-darker);
}
.chat-box-right {
  background-color: #79bbff;
}
.chat-box-left::before {
  content: '';
  position: absolute;
  width: 0;
  height: 0;
  left: -20px;
  top:5px;
  border: 10px solid;
  border-color: transparent var(--el-fill-color-darker) transparent transparent;
}
.chat-box-right::after {
  content: '';
  position: absolute;
  width: 0;
  height: 0;
  right: -20px;
  top:5px;
  border: 10px solid;
  border-color: transparent transparent transparent  #79bbff;
}
.time {
  display: flex;
  flex-direction: column-reverse;
  margin: 0 1rem;
  color: #909399;
}
</style>